#encoding:utf-8
import os
import psutil
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from datetime import datetime
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

RST = 17
DC = 17
SPI_PORT = 0
SPI_DEVICE = 0

disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, 
spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))
disp.begin()
disp.clear()
disp.display()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0,0,width,height), outline=0, fill=0)
padding = 1
top = padding
x = padding
font = ImageFont.truetype('DejaVuSans.ttf', 11)
#font = ImageFont.truetype('android.ttf', 11)


def show_info():
    while (1):
        draw.rectangle((0,0,width,height), outline=0, fill=0)
        # get, display date and time
        draw.text((1, 1), str(datetime.now().strftime('%a %b %d %H:%M:%S')),font=font, fill=1)
        # get, return CPU's current temperature
        def cpu_temp():
            tempF = (((int(open('/sys/class/thermal/thermal_zone0/temp').read())/1000)))
            return "CPU TEMP: %s*C" % str(tempF)

        # display CPU temp
        draw.text((1, 15),    cpu_temp(),  font=font, fill=1)

        # get, return wlan0's current IP address
        def wlan_ip():
            #f = os.popen('ifconfig wlan0 | grep "inet\ addr" | cut -c 21-33')
            f = os.popen('hostname -i')
            ip = str(f.read())
            # strip out trailing chars for cleaner output
            return "IP: %s" % ip.rstrip('\r\n')

        # display the IP address
        draw.text((1, 28),    wlan_ip(),  font=font, fill=1)

        # get amount of memory in use
        def mem_usage():
            usage = psutil.virtual_memory()
            return "MEM USE:  %sKB" % (int(str(usage.used)) / 1024)

        # display amount of free memory
        draw.text((1, 41),    mem_usage(),  font=font, fill=1)

        # get disk usage
        def disk_usage(dir):
            usage = psutil.disk_usage(dir)
            return "SD CARD IN USE: %.0f%%" % (usage.percent)

        # display disk usage
        draw.text((1, 53), disk_usage('/'),  font=font, fill=1)
    
        disp.image(image)
        disp.display()
        time.sleep(1)

if __name__=="__main__":
    try:
        show_info()
    except:
        draw.rectangle((0,0,width,height),outline=0,fill=0)
        draw.text((30,30),"Bey! Bey!",font=font,fill=1)
        disp.image(image)
        disp.display()
        time.sleep(1)
        disp.clear()
        disp.display()


